<template>
  <div class="player" v-show="playlist.length">
    <transition
      name="normal"
      @enter="enter"
      @after-enter="afterEnter"
      @leave="leave"
      @afterLeave="afterLeave"
    >
      <div class="normal-player" v-show="fullScreen">
        <div class="background">
          <img :src="currentSong.pic" />
        </div>
        <!-- <div style="width:100%;height:70px;"></div> -->
        <div class="top">
          <div class="back" @click="goBack">
            <i class="icon-back"></i>
          </div>
          <h1 class="title">{{ currentSong.name }}</h1>
          <h2 class="subtitle">{{ currentSong.singer }}</h2>
        </div>

        <van-swipe
          :initial-swipe="swipeIndex"
          @change="onChange"
          :show-indicators="false"
        >
          <van-swipe-item>
            <div
              class="middle"
              @touchstart.prevent="onMiddleTouchStart"
              @touchmove.prevent="onMiddleTouchMove"
              @touchend.prevent="onMiddleTouchEnd"
            >
              <div class="middle-l">
                <div ref="cdWrapperRef" class="cd-wrapper">
                  <div ref="cdRef" class="cd">
                    <img
                      ref="cdImageRef"
                      class="image"
                      :class="cdCls"
                      :src="currentSong.pic"
                    />
                  </div>
                </div>
                <div class="playing-lyric-wrapper">
                  <div class="playing-lyric">{{ playingLyric }}</div>
                </div>
              </div>
            </div>
          </van-swipe-item>
          <van-swipe-item>
            <Scroll class="middle-r" ref="lyricScrollRef">
              <div class="lyric-wrapper">
                <div v-if="currentLyric" ref="lyricListRef">
                  <p
                    class="text"
                    :class="{ current: currentNum === index }"
                    v-for="(line, index) in currentLyric.lines"
                    :key="line.num"
                  >
                    {{ line.txt }}
                  </p>
                </div>
                <div class="pure-music" v-show="pureMusicLyric">
                  <p>{{ pureMusicLyric }}</p>
                </div>
              </div>
            </Scroll>
            <!-- <van-list :immediate-check="false">
            <div v-if="currentLyric">
              <p
                class="text"
                v-for="line in currentLyric.lines"
                :key="line.num"
              >
                {{ line.txt }}
              </p>
            </div>
            <div class="pure-music">
              <p>{{ pureMusicLyric }}</p>
            </div>
          </van-list> -->
          </van-swipe-item>
        </van-swipe>

        <div style="width:100%;height:135px;"></div>

        <div class="bottom">
          <div class="dot-wrapper">
            <span class="dot" :class="{ active: swipeIndex === 0 }"></span>
            <span class="dot" :class="{ active: swipeIndex === 1 }"></span>
          </div>
          <div class="progress-wrapper">
            <span class="time time-l">{{ formatTime(currentTime) }}</span>
            <div class="progress-bar-wrapper">
              <ProgressBbar
                ref="barRef"
                :progress="progress"
                @progress-changing="onProgressChanging"
                @progress-changed="onProgressChanged"
              ></ProgressBbar>
            </div>
            <span class="time time-r">{{
              formatTime(currentSong.duration)
            }}</span>
          </div>
          <div class="operators">
            <div class="icon i-left">
              <i @click="changeMode" :class="modeIcon"></i>
            </div>
            <div class="icon i-left" :class="disableCls">
              <i @click="prev" class="icon-prev"></i>
            </div>
            <div class="icon i-center" :class="disableCls">
              <i @click="togglePlay" :class="playIcon"></i>
            </div>
            <div class="icon i-right" :class="disableCls">
              <i @click="next" class="icon-next"></i>
            </div>
            <div class="icon i-right">
              <i
                @click="toggleFavorite(currentSong)"
                :class="getFavoriteIcon(currentSong)"
              ></i>
            </div>
          </div>
        </div>
      </div>
    </transition>

    <MiniPlayer :progress="progress" :toggle-play="togglePlay" />
    <audio
      ref="audioRef"
      @pause="pause"
      @canplay="ready"
      @error="error"
      @timeupdate="updateTime"
      @ended="end"
    ></audio>
  </div>
</template>
<script>
import Scroll from '@/components/Scroll'
import { useStore } from 'vuex'
import { computed, watch, ref, nextTick } from 'vue'
import useMode from './use-mode'
import useFavorite from './use-favorite'
import useCd from './use-cd'
import useLyric from './use-lyric'
import useAnimation from './use-animation'
import ProgressBbar from './progress-bar.vue'
import { formatTime } from '@/assets/js/util'
import { PLAY_MODE } from '@/assets/js/constant.js'
import MiniPlayer from './mini-player.vue'
export default {
  name: 'Player',
  components: { ProgressBbar, Scroll, MiniPlayer },
  setup() {
    const audioRef = ref(null)
    const barRef = ref(null)
    const store = useStore()
    const songReady = ref(false)
    const currentTime = ref(0) // 歌曲播放时长
    const swipeIndex = ref(0) // 轮播
    let progressChing = false
    // 播放状态 全屏或收缩
    const fullScreen = computed(() => store.state.fullScreen)
    // 当前播放歌曲
    const currentSong = computed(() => store.getters.currentSong)
    // 是否播放
    const playing = computed(() => store.state.playing)

    const { modeIcon, changeMode } = useMode()
    const { getFavoriteIcon, toggleFavorite } = useFavorite()
    const { cdCls, cdRef, cdImageRef } = useCd()
    const {
      currentLyric,
      currentNum,
      playLyric,
      lyricScrollRef,
      lyricListRef,
      stopLyric,
      pureMusicLyric,
      playingLyric
    } = useLyric({
      songReady,
      currentTime
    })
    const {
      cdWrapperRef,
      enter,
      afterEnter,
      leave,
      afterLeave
    } = useAnimation()

    // 获取播放列表
    const playlist = computed(() => store.state.playlist)
    // 当前播放歌曲的索引
    const currentIndex = computed(() => store.state.currentIndex)
    // 播放进度
    const progress = computed(() => {
      return currentTime.value / currentSong.value.duration
    })

    // 播放模式
    const playMode = computed(() => store.state.playMode)
    // 暂停或播放图标
    const playIcon = computed(() => {
      return playing.value ? 'icon-pause' : 'icon-play'
    })
    // 禁止点击
    const disableCls = computed(() => {
      return songReady.value ? '' : 'disable'
    })
    watch(currentSong, newSong => {
      if (!newSong.id || !newSong.url) {
        return false
      }
      currentTime.value = 0
      swipeIndex.value = 0
      songReady.value = false
      const audioEl = audioRef.value
      audioEl.src = newSong.url
      audioEl.play()
      store.commit('setPlayingState', true)
      store.dispatch('setPlayHistory', { song: newSong })
    })
    watch(playing, newPlaying => {
      if (!songReady.value) {
        return
      }
      const audioEl = audioRef.value
      if (newPlaying) {
        audioEl.play()
        playLyric()
      } else {
        audioEl.pause()
        stopLyric()
      }
    })
    watch(fullScreen, async newFullScreen => {
      if (newFullScreen) {
        await nextTick()
        barRef.value.setOffset(progress.value)
      }
    })

    // 全屏缩小
    function goBack() {
      store.commit('setFullScreen', false)
    }
    // 点击播放暂停按钮
    function togglePlay() {
      if (!songReady.value) {
        return
      }
      store.commit('setPlayingState', !playing.value)
    }
    // 监听待机
    function pause() {
      store.commit('setPlayingState', false)
    }
    // 上一首
    function prev() {
      const list = playlist.value
      if (!songReady.value || !list.length) {
        return
      }
      if (list.length === 1) {
        loop()
      } else {
        let index = currentIndex.value - 1
        if (index === -1) {
          index = list.length - 1
        }
        store.commit('setCurrentIndex', index)
      }
    }
    // 下一首
    function next() {
      const list = playlist.value
      if (!songReady.value || !list.length) {
        return
      }
      if (list.length === 1) {
      } else {
        let index = currentIndex.value + 1
        if (index === list.length) {
          index = 0
        }
        store.commit('setCurrentIndex', index)
      }
    }
    // 循环播放
    function loop() {
      const audioEl = audioRef.value
      audioEl.currentTime = 0
      audioEl.play()
      store.commit('setPlayingState', true)
    }
    // ready
    function ready() {
      if (songReady.value) {
        return
      }
      songReady.value = true
      playLyric()
    }
    // ready 出错
    function error() {
      songReady.value = true
    }
    // audio 原生事件,更新播放时间
    function updateTime(e) {
      if (!progressChing) {
        currentTime.value = e.target.currentTime
      }
    }
    // 进度条组件 进度条改变
    function onProgressChanging(progress) {
      progressChing = true
      currentTime.value = currentSong.value.duration * progress
      playLyric()
      stopLyric()
    }
    // 进度条组件 进度条改变结束
    function onProgressChanged(progress) {
      progressChing = false
      audioRef.value.currentTime = currentTime.value =
        currentSong.value.duration * progress
      if (!playing.value) {
        store.commit('setPlayingState', true)
      }
      playLyric()
    }
    // 当前歌曲播放结束
    function end() {
      currentTime.value = 0
      if (playMode.value === PLAY_MODE.loop) {
        loop()
      } else {
        next()
      }
    }
    const onChange = index => {
      swipeIndex.value = index
    }

    return {
      // animation
      cdWrapperRef,
      enter,
      afterEnter,
      leave,
      afterLeave,
      barRef,
      // lyric
      playingLyric,
      pureMusicLyric,
      lyricScrollRef,
      lyricListRef,
      currentLyric,
      currentNum,
      // swipe
      onChange,
      swipeIndex,
      // cd
      cdCls,
      cdRef,
      cdImageRef,
      //
      end,
      onProgressChanging,
      onProgressChanged,
      formatTime,
      updateTime,
      progress,
      currentTime,
      togglePlay,
      pause,
      goBack,
      audioRef,
      fullScreen,
      currentSong,
      playIcon,
      prev,
      next,
      ready,
      disableCls,
      error,
      modeIcon,
      changeMode,
      getFavoriteIcon,
      toggleFavorite,
      playlist
    }
  }
}
</script>
<style lang="scss" scoped>
.player {
  .normal-player {
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    z-index: 9999;
    background: $color-background;
    display: flex;
    flex-direction: column;
    .background {
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      z-index: -1;
      opacity: 0.6;
      filter: blur(20px);

      img {
        width: 100%;
        height: 100%;
      }
    }
    .top {
      position: relative;
      margin-bottom: 20px;
      .back {
        position: absolute;
        top: 0;
        left: 6px;
        z-index: 50;
      }
      .icon-back {
        display: block;
        padding: 9px;
        font-size: $font-size-large-x;
        color: $color-theme;
        transform: rotate(-90deg);
      }
      .title {
        width: 70%;
        margin: 0 auto;
        line-height: 40px;
        text-align: center;
        @include no-wrap();
        font-size: $font-size-large;
        color: $color-text;
      }
      .subtitle {
        line-height: 20px;
        text-align: center;
        font-size: $font-size-medium;
        color: $color-text;
      }
    }
    .van-swipe {
      flex: 1;
      .van-swipe-item {
        width: 100%;
        height: 100%;
        .middle-r {
          display: inline-block;
          vertical-align: top;
          width: 100%;
          height: 100%;
          overflow: hidden;
          .lyric-wrapper {
            width: 80%;
            margin: 0 auto;
            overflow: hidden;
            text-align: center;
            .text {
              line-height: 32px;
              color: $color-text-l;
              font-size: $font-size-medium;
              &.current {
                // color: $color-text;
                color: $color-theme;
              }
            }
            .pure-music {
              padding-top: 50%;
              line-height: 32px;
              color: $color-text-l;
              font-size: $font-size-medium;
            }
          }
        }
        // .van-list {
        //   width: 100%;
        //   height: 100%;
        //   .text {
        //     line-height: 32px;
        //     color: $color-text-l;
        //     font-size: $font-size-medium;
        //     text-align: center;
        //     &.current {
        //       color: $color-text;
        //     }
        //   }
        //   .pure-music {
        //     padding-top: 50%;
        //     line-height: 32px;
        //     color: $color-text-l;
        //     font-size: $font-size-medium;
        //   }
        // }
      }
    }
    .middle {
      // position: fixed;
      // width: 100%;
      // top: 80px;
      // bottom: 170px;
      // white-space: nowrap;
      // font-size: 0;
      .middle-l {
        display: inline-block;
        vertical-align: top;
        position: relative;
        width: 100%;
        height: 0;
        padding-top: 80%;
        .cd-wrapper {
          position: absolute;
          left: 10%;
          top: 0;
          width: 80%;
          box-sizing: border-box;
          height: 100%;
          .cd {
            width: 100%;
            height: 100%;
            border-radius: 50%;
            img {
              position: absolute;
              left: 0;
              top: 0;
              width: 100%;
              height: 100%;
              box-sizing: border-box;
              border-radius: 50%;
              border: 10px solid rgba(255, 255, 255, 0.1);
            }
            .playing {
              animation: rotate 20s linear infinite;
            }
          }
        }
        .playing-lyric-wrapper {
          width: 80%;
          margin: 30px auto 0 auto;
          overflow: hidden;
          text-align: center;
          .playing-lyric {
            height: 20px;
            line-height: 20px;
            font-size: $font-size-medium;
            color: $color-text-l;
          }
        }
      }
    }
    .bottom {
      position: absolute;
      bottom: 30px;
      width: 100%;
      height: 100px;
      .dot-wrapper {
        text-align: center;
        font-size: 0;
        .dot {
          display: inline-block;
          vertical-align: middle;
          margin: 0 4px;
          width: 8px;
          height: 8px;
          border-radius: 50%;
          background: $color-text-l;
          &.active {
            width: 20px;
            border-radius: 5px;
            background: $color-text-ll;
          }
        }
      }
      .progress-wrapper {
        display: flex;
        align-items: center;
        width: 80%;
        margin: 0px auto;
        padding: 10px 0;
        .time {
          color: $color-text;
          font-size: $font-size-small;
          flex: 0 0 40px;
          line-height: 30px;
          width: 40px;
          &.time-l {
            text-align: left;
          }
          &.time-r {
            text-align: right;
          }
        }
        .progress-bar-wrapper {
          flex: 1;
        }
      }
      .operators {
        display: flex;
        align-items: center;
        .icon {
          flex: 1;
          color: $color-theme;
          &.disable {
            color: $color-theme-d;
          }
          i {
            font-size: 30px;
          }
        }
        .i-left {
          text-align: right;
        }
        .i-center {
          padding: 0 20px;
          text-align: center;
          i {
            font-size: 40px;
          }
        }
        .i-right {
          text-align: left;
        }
        .icon-favorite {
          color: $color-sub-theme;
        }
      }
    }
    &.normal-enter-active,
    &.normal-leave-active {
      transition: all 0.6s;
      .top,
      .bottom {
        transition: all 0.6s cubic-bezier(0.45, 0, 0.55, 1);
      }
    }
    &.normal-enter-from,
    &.normal-leave-to {
      opacity: 0;
      .top {
        transform: translate3d(0, -100px, 0);
      }
      .bottom {
        transform: translate3d(0, 100px, 0);
      }
    }
  }
}
</style>
